package com.ylkj.wx.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ylkj.wx.constant.WeiXConstant;
import com.ylkj.wx.dto.OrderInfoDTO;
import com.ylkj.wx.dto.UnifiedOrderDto;
import com.ylkj.wx.service.OrderInfoService;
import com.ylkj.wx.utils.CommonUtil;
import com.ylkj.wx.utils.UUIDUtil;
import com.ylkj.wx.utils.WeixCommonUtil;
import com.ylkj.wx.utils.XMLUtil;

/**
 * 订单controller--
 * @author baoy
 *
 */
@Controller
@RequestMapping("/order")
public class OrderInfoComtroller {
	private static final Logger LOGGER = LoggerFactory.getLogger(OrderInfoComtroller.class);
	@Autowired
	public OrderInfoService orderService;
	
	@RequestMapping(value = "/createOrder", method = RequestMethod.POST)
	public @ResponseBody boolean createOrder(@RequestBody OrderInfoDTO order,
												HttpServletRequest request,
												HttpServletResponse response) {
	
		UnifiedOrderDto unifiedorder = new UnifiedOrderDto();
		unifiedorder.setAppId(WeiXConstant.appid);
		unifiedorder.setMchId(WeiXConstant.mch_id);
		unifiedorder.setDeviceInfo(WeiXConstant.device_info);
		unifiedorder.setBody("打赏订单");
		String nonce = UUIDUtil.getUUID();
	    unifiedorder.setNonceStr(nonce);

        unifiedorder.setNotifyUrl(WeiXConstant.domain_url+"order/wxPayCallBack");
        unifiedorder.setTradeType(WeiXConstant.trade_type);
        
	    //商户订单号 out_trade_no
        unifiedorder.setOutTradeNo(order.getOrderNo());
        //微信钱币以分为单位，所以乘100换算成元
        //update by baoy on 20170804 
        String totalFee = String.valueOf(Math.round(order.getPayMoney()*100));
        //String totalFee = String.valueOf("100");
        unifiedorder.setTotalFee(totalFee);
        
        unifiedorder.setSpbillCreateIp(CommonUtil.getIpAddr(request)); //获取访问IP
        //"wap_url": "",//WAP网站URL地址        "wap_name": ""  //WAP 网站名
        unifiedorder.setSceneInfo("{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"https://pay.qq.com\",\"wap_name\": \"打赏订单\"}}");
        //unifiedorder.setOpenid(openId);
        unifiedorder = WeixCommonUtil.unifiedOrder(unifiedorder);
        try {
			response.sendRedirect(unifiedorder.getMwebUrl());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/wxPayCallBack", method = { RequestMethod.GET,	RequestMethod.POST})
	public void wxPayCallBack(HttpServletRequest request,HttpServletResponse response) {
		PrintWriter pw = null;
		try {
			InputStream inStream = request.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
			outSteam.close();
			inStream.close();
			// 获取微信调用我们notify_url的返回信息
			String result = new String(outSteam.toByteArray(), "utf-8");
			LOGGER.error("PayCallBackController wxPayCallBack result=" + result);
			// 接受微信参数 解析返回的数据
			Map<Object, Object> map = XMLUtil.doXMLParse(result);
			LOGGER.error("PayCallBackController wxPayCallBack map："+ map.toString());
			// 处理自己的业务回调成功 获取 订单的ID
			String orderCode = String.valueOf(map.get("out_trade_no"));

			if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
				// 微信返回成功信息，处理订单状态为已支付，处理代金券和验证码
				
			
			} else {
				
			}
		} catch (Exception e) {

		} finally {
			if (null != pw) {
				pw.close();
			}
		}
	}
}
